<template>
  <u-loading-page :bg-color="'#e8e8e8'"  :loading="loading"></u-loading-page>
  <view v-show="!loading"  class="container" style="background: black">
    <u-navbar
        :autoBack="true"
        leftIconColor="white"
        :title-style="{color: 'white'}"
        bgColor="transparent"
    >
    </u-navbar>
    <image  class="image-container"  :src="avatar"
           style="width: 100%;position: relative"
           mode="widthFix"></image>
    <view style="width: 100%;height: 100vh">
      <Cropper
          v-if="showCropper"
          @close="showCropper=false"
          @drawSuccess="drawSuccess"
          @drawFail="drawFail"
          @uploadSuccess="uploadSuccess"
          @uploadFail="uploadFail"

          shape="circle"
      ></Cropper>
    </view>
    <view class='cropper-config' :style="{justifyContent: !owner ? 'center' : 'space-between'}">
      <view class="cropper-choose"
            v-if="owner"
            style="background-color: #444343;color:#fff;"
            @click="showCropper=true">更换头像
      </view>
      <view class="cropper-confirm"
            style="background-color: #444343;color:#fff;"
            @click="savePhotosToAlbum(avatar)">下载
      </view>
    </view>

  </view>
</template>

<script>
//  1.引入项目
import OkingtzCropper from '@/uni_modules/okingtz-cropper/components/okingtz-cropper/okingtz-cropper'
import colorThief from "miniapp-color-thief";
import Cropper from "@/components/circle-avatar-cropper/cropper.vue";
import {getToken, getUserId} from "@/utils/auth";
import {alterFrontUserAvatar, alterFrontUserBackground} from "@/api/user";
import {downloadTempFile, savePhotosToAlbum} from "@/utils/downloadFile";

export default {
  components: {
    Cropper,
    //2.使用组件
    OkingtzCropper
  },
  data() {
    return {
      loading:true,
      showCropper:false,
      showCanvas:true,
      // 5.定义自己的数据
      palette: "",
      canvasWidth: 0,
      canvasHeight: 0,
      owner:false,
      // 用户信息
      userInfo: {},
      img: '',
      avatar: '',
      mainColorHex: ''
    }
  },
  onReady() {

  },
  onLoad(options) {
    if (options.url !== undefined) {
      this.avatar = options.url
    }
    let ownerId = getUserId();
    this.owner = ownerId == options.ownerId
    setTimeout(() => {
      this.loading = false
    }, 1000)
  },
  methods: {
    savePhotosToAlbum,
    // 3.定义自己的回调函数
    drawSuccess(res){
      // console.log('裁切成功',res)
      this.showCropper = false
      let _this = this
      uni.uploadFile({
        url: this.$BASE_UPLOAD, //仅为示例，非真实的接口地址
        filePath: res.tempFilePath,
        name: 'file',
        header: {
          'Authorization': getToken(),
        },
        success: (uploadFileRes) => {
          let result = (JSON.parse(uploadFileRes.data)).data.url
          alterFrontUserAvatar(result).then(res => {
            if(res.code == 200 && res?.data === undefined){
              _this.avatar = result
              setTimeout(()=>{
                uni.showToast({
                  title: '设置成功',
                  icon: 'none'
                })
              },1000)
            }else {
              setTimeout(()=>{
                uni.showToast({
                  title: res.data,
                  icon: 'none',
                  duration: 2000
                })
              },1000)
            }
          })

        },
        fail: (err) => {
          console.log(err)
        }
      })

    },

    drawFail(res){console.log('裁切失败',res)},
    uploadSuccess(res){console.log('上传成功',res)},
    uploadFail(res){console.log('上传失败',res)},
    alterAvatar(){
      this.showCropper = true
      // this.uploading = true

    },
    // 转换RGB到HEX格式
    rgbToHex(r, g, b) {
      return ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
    }
  }
}
</script>

<style lang="scss" scoped>
.canvas-container canvas {
  width: 100%;
  height: calc(100% * (9 / 16)); /* 这里假设支持CSS calc函数 */
  object-fit: contain; /* 部分环境可能不支持这个属性，仅用于理想情况下的比例保持 */
  position: absolute;
  top: 60%;
  left: 0;
  transform: translateY(-50%);
}
.image-container{
  position: absolute;
  top: 25%;
  left: 0;
}
.container{
  width: 100%;
  height: 100vh;
  overflow-y: hidden;
  position: relative;
}

.cropper-config {
  padding: 50rpx 40rpx;
  display: flex;
  justify-content: space-between;
  position: absolute;
  bottom: 50px;
  width: 88vw;
}

.cropper-choose, .cropper-confirm {
  background-color: rgba(0, 0, 0, 0.1);
  color: #FFFFFF;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 8rpx;
  text-align: center;
  width: 300rpx;
  font-size: 30rpx;
  font-weight: 600;
}
</style>
